package com.gx.smart.building.ui.knowledge

import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.angcyo.tablayout.delegate2.ViewPager2Delegate
import com.gx.smart.base.BaseMVVMActivityV3
import com.gx.smart.building.R
import com.gx.smart.building.databinding.ActivityKnowledgeBinding
import com.gx.smart.building.ui.knowledge.adapter.PageAdapter
import com.gx.smart.building.ui.knowledge.fragment.KnowledgeFragment
import com.gx.smart.building.ui.knowledge.model.KnowledgeType
import com.gx.smart.building.ui.knowledge.viewmodel.KnowledgeViewModel

class KnowledgeActivity : BaseMVVMActivityV3<KnowledgeViewModel>() {
    private lateinit var viewBinding: ActivityKnowledgeBinding
    private lateinit var adapter: PageAdapter
    override fun onBindViewModel(): Class<KnowledgeViewModel> = KnowledgeViewModel::class.java

    override fun onBindLayout(): Int = R.layout.activity_knowledge

    override fun getToolbarTitle(): String = "知识库分类"

    override fun initContentView(root: ViewGroup?) {
        viewBinding = ActivityKnowledgeBinding.inflate(layoutInflater, root, true)
        val delegate = ViewPager2Delegate(viewBinding.viewpager, viewBinding.tabLayout)
        viewBinding.tabLayout.setupViewPager(delegate)
        adapter = PageAdapter(this)
        viewBinding.viewpager.adapter = adapter
        viewBinding.viewpager.isUserInputEnabled = false
    }

    override fun initData() {
        viewModel.queryKnowledgeTypeTreeList().observe(this) {
            it?.forEach { item ->
                val itemView: View =
                    layoutInflater.inflate(R.layout.item_knowledge, viewBinding.tabLayout, false)
                val tabItem = itemView.findViewById<TextView>(R.id.tabItem)
                tabItem.text = item.baseTypeLabel
                viewBinding.tabLayout.addView(itemView)
                val newChildrenList = arrayListOf<KnowledgeType>()
                item.children.map { child ->
                    val newSubChildrenList = arrayListOf<KnowledgeType>()
                    child.children?.forEach { cc ->
                        newSubChildrenList.add(KnowledgeType(cc.id, cc.baseTypeLabel, null))
                    }
                    newChildrenList.add(
                        KnowledgeType(
                            child.id,
                            child.baseTypeLabel,
                            newSubChildrenList
                        )
                    )
                }
                adapter.add(KnowledgeFragment.newInstance(newChildrenList))
            }
        }
    }
}